package com.example.cato_api.controller;


import com.example.cato_data.data.TacoRepository;
import com.example.cato_entity.entity.Taco;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.hateoas.server.EntityLinks;
import org.springframework.hateoas.server.RepresentationModelProcessor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

@RepositoryRestController //用在控制器类，这样控制器类所有映射的基础路径就会与Spring Data Rest 断点配置的基础路径相同
//这个注解不能确保把返回值写到数据体中，所以要么加上@ResponsBody，要么返回包装响应数据的ResponseEntity
public class RecentController {

    private TacoRepository tacoRepo;


    public RecentController(TacoRepository tacoRepo) {
        this.tacoRepo = tacoRepo;
    }


    @GetMapping(path = "/tacos/recent", produces = "application/json")
    public ResponseEntity<CollectionModel<TacoEntityModel>> recentTacos() {
        PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
        List<Taco> tacos = tacoRepo.findAll(page).getContent();
        CollectionModel<TacoEntityModel> recentSources = new TacoEntityModelAssembler().toCollectionModel(tacos);
        recentSources.add(linkTo(methodOn(RecentController.class).recentTacos()).withRel("recents"));
        return new ResponseEntity<>(recentSources, HttpStatus.OK);
    }


    /*
    通过声明资源处理器bean，我们可以为Spring Data REST 自动包含的链接链表添加链接，Spring HATEOAS会自动发现这个bean 并将其用到相应的资源上
     */
    @Bean
    public RepresentationModelProcessor<PagedModel<EntityModel<Taco>>> tacoProcessor(EntityLinks links) {
        return new RepresentationModelProcessor<PagedModel<EntityModel<Taco>>>() {
            @Override
            public PagedModel<EntityModel<Taco>> process(PagedModel<EntityModel<Taco>> model) {
                model.add(links.linkFor(Taco.class).slash("recent").withRel("recents"));
                return model;
            }
        };
    }
}
